package com.key.config;

import com.key.SafeUtil;
import com.key.center.KeyCenter;
import com.key.center.KeyCenterBuildFactory;
import com.key.unusual.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author dzl
 * @Date 2021/11/11 4:07 下午
 * 抽象类
 */
@Slf4j
public class EncrytionProperties implements EnvironmentPostProcessor {
    private KeyCenter keyCenter = KeyCenterBuildFactory.KEY_CENTER;

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Iterator<PropertySource<?>> iterator = environment.getPropertySources().iterator();
        Map<String, Object> map = new HashMap(16);
        while (iterator.hasNext()) {
            PropertySource<?> next = iterator.next();
            /*查看配置文件的数据源*/
            if (next instanceof OriginTrackedMapPropertySource) {
                OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) next;
                /*拿到所有属性名*/
                String[] propertyNames = source.getPropertyNames();
                /*在propertyNames里面优先级高的会在数组的前面*/
                for (String x : propertyNames) {
                    String value = source.getProperty(x).toString();
                    if (value.startsWith(keyCenter.EncryptionPrefix()) && !map.containsKey(x)) {
                        try {
                            map.put(x, SafeUtil.decrypt(value.substring(keyCenter.EncryptionPrefix().length())));
                        } catch (Exception e) {
                            Assert.error(String.format("%s:KeyCenter解密数据该数据发生异常", value));
                        }
                    }
                }
            }
        }
        environment.getPropertySources().addFirst(new OriginTrackedMapPropertySource(keyCenter.EncryptionPrefix(), map));
    }

}
